<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8"/>
    <meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0">
    <title>订单详情 - 钢域云贸</title>
    <link rel="icon" href="/uploads/logo.png" type="image/x-icon"/>
    <link rel="shortcut icon" href="/uploads/logo.png" type="image/x-icon"/>
    <link rel="stylesheet" type="text/css" href="/css/public.css"/>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css"/>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        /* 自定义弹窗样式，模仿图片中的效果 */
        .success-modal {
            position: fixed;
            top: 20%;
            left: 50%;
            transform: translateX(-50%);
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            z-index: 1000;
            width: 300px;
            text-align: center;
        }
        .success-modal h3 {
            font-size: 1.2rem;
            margin-bottom: 20px;
            color: #333;
        }
        .success-modal .btn-confirm {
            background-color: #3b82f6; /* 蓝色按钮 */
            color: white;
            padding: 8px 20px;
            border-radius: 20px;
            border: none;
            cursor: pointer;
        }
        .success-modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 999;
            display: none;
        }

             /* 订单详情容器 */
         .order-detail {
             max-width: 1200px;
             margin: 2rem auto;
             padding: 2rem;
             background-color: #fff;
             border-radius: 8px;
             box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
         }

        /* 各部分标题 */
        .detail-section h3 {
            font-size: 1.25rem;
            font-weight: 600;
            color: #333;
            padding-bottom: 0.75rem;
            border-bottom: 1px solid #e5e7eb;
            margin-bottom: 1.5rem;
            position: relative;
        }

        .detail-section h3::after {
            content: "";
            position: absolute;
            left: 0;
            bottom: -1px;
            width: 80px;
            height: 2px;
            background-color: #3b82f6;
        }

        /* 信息行样式 */
        .info-row {
            display: flex;
            margin-bottom: 1rem;
            line-height: 1.5;
        }

        .info-label {
            font-weight: 500;
            color: #666;
            min-width: 100px;
            margin-right: 1rem;
        }

        /* 商品表格样式 */
        .product-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 1rem;
            font-size: 0.9rem;
        }

        .product-table th {
            background-color: #f8fafc;
            padding: 0.75rem 1rem;
            text-align: left;
            font-weight: 600;
            color: #475569;
            border-bottom: 1px solid #e2e8f0;
        }

        .product-table td {
            padding: 0.75rem 1rem;
            border-bottom: 1px solid #e2e8f0;
            vertical-align: top;
        }

        .product-table tr:hover td {
            background-color: #f8fafc;
        }

        /* 按钮区域样式 */
        .order-actions {
            display: flex;
            gap: 1rem;
            margin: 2rem 0;
        }

        .order-back {
            text-align: right;
        }

        /* 按钮基础样式 */
        .btn-pay, .btn-cancel, .btn-confirm, .btn-back {
            padding: 0.5rem 1.25rem;
            border-radius: 4px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .btn-pay {
            background-color: #3b82f6;
            color: white;
            border: 1px solid #3b82f6;
        }

        .btn-pay:hover {
            background-color: #2563eb;
        }

        .btn-cancel {
            background-color: white;
            color: #64748b;
            border: 1px solid #e2e8f0;
        }

        .btn-cancel:hover {
            background-color: #f8fafc;
            color: #475569;
        }

        .btn-confirm {
            background-color: #10b981;
            color: white;
            border: 1px solid #10b981;
        }

        .btn-confirm:hover {
            background-color: #059669;
        }

        .btn-back {
            background-color: #f1f5f9;
            color: #475569;
            border: 1px solid #e2e8f0;
        }

        .btn-back:hover {
            background-color: #e2e8f0;
        }

        /* 错误提示 */
        .text-danger {
            color: #ef4444;
        }

        /* 响应式调整 */
        @media (max-width: 768px) {
            .order-detail {
                padding: 1rem;
            }

            .product-table {
                display: block;
                overflow-x: auto;
            }

            .info-row {
                flex-direction: column;
                margin-bottom: 1.5rem;
            }

            .info-label {
                margin-bottom: 0.25rem;
            }

            .order-actions {
                flex-direction: column;
            }
        }

        /* 支付方式选择框 */
        select {
            padding: 0.25rem 0.5rem;
            border: 1px solid #e2e8f0;
            border-radius: 4px;
            background-color: white;
        }

        select:disabled {
            background-color: #f8fafc;
            color: #64748b;
        }

    </style>
</head>
<body>
<th:block th:replace="~{/header.html}"></th:block>
<div class="container">
    <!-- 显示错误信息 -->
    <div th:if="${error}" class="error-message">
        <span th:text="${error}"></span>
    </div>
    <div class="order-detail">
        <div class="detail-section">
            <h3>订单信息</h3>
            <div class="info-row">
                <span class="info-label">订单编号:</span>
                <span th:text="${order.orderNo}"></span>
            </div>
            <div class="info-row">
                <span class="info-label">总金额:</span>
                <span th:text="'￥' + ${#numbers.formatDecimal(order.totalAmount, 1, 2)}"></span>
            </div>
            <div class="info-row">
                <span class="info-label">订单状态:</span>
                <span th:text="${order.status == 'PENDING'? '待支付' :
                                order.status == 'PAID'? '已支付' :
                                order.status == 'SHIPPED'? '已发货' :
                                order.status == 'COMPLETED'? '已完成' :
                                order.status == 'CANCELLED'? '已取消' : order.status}">
                </span>
            </div>
            <div class="info-row">
                <span class="info-label">支付方式:</span>
                <select th:name="paymentMethod" th:value="${order.paymentMethod}"
                        th:disabled="${order.status != 'PENDING'}" id="paymentMethodSelect">
                    <option value="BANK_TRANSFER" th:selected="${order.paymentMethod == 'BANK_TRANSFER'}">银行转账</option>
                    <option value="ONLINE_PAYMENT" th:selected="${order.paymentMethod == 'ONLINE_PAYMENT'}">在线支付</option>
                    <option value="CREDIT" th:selected="${order.paymentMethod == 'CREDIT'}">信用卡支付</option>
                </select>
            </div>
            <div class="info-row">
                <span class="info-label">下单时间:</span>
                <span th:text="${#dates.format(order.createTime, 'yyyy-MM-dd HH:mm')}"></span>
            </div>
        </div>
        <div class="detail-section">
            <h3>收货信息</h3>
            <div class="info-row">
                <span class="info-label">联系人:</span>
                <span th:text="${order.contactName}"></span>
            </div>
            <div class="info-row">
                <span class="info-label">联系电话:</span>
                <span th:text="${order.contactPhone}"></span>
            </div>
            <div class="info-row">
                <span class="info-label">收货地址:</span>
                <span th:text="${order.deliveryAddress}"></span>
            </div>
        </div>
        <div class="detail-section">
            <h3>物流信息</h3>
            <div class="info-row" th:if="${order.shippingCompany} != null">
                <span class="info-label">物流公司:</span>
                <span th:text="${order.shippingCompany}"></span>
            </div>
            <div class="info-row" th:if="${order.trackingNumber} != null">
                <span class="info-label">物流单号:</span>
                <span th:text="${order.trackingNumber}"></span>
            </div>
            <div class="info-row" th:if="${order.shippingAddress} != null">
                <span class="info-label">发货地址:</span>
                <span th:text="${order.shippingAddress}"></span>
            </div>
            <div class="info-row" th:if="${order.shippingCompany} == null">
                <span>暂无物流信息</span>
            </div>
        </div>
        <div class="detail-section">
            <h3>商品信息</h3>
            <table class="product-table">
                <thead>
                <tr>
                    <th>商品名称</th>
                    <th>规格</th>
                    <th>单价</th>
                    <th>数量</th>
                    <th>库存</th>
                    <th>总价</th>
                    <th>供应商</th>
                </tr>
                </thead>
                <tbody>
                <tr th:each="item : ${order.items}">
                    <td th:text="${item.productName}">商品名称</td>
                    <td th:text="${item.specification}">规格</td>
                    <td th:text="'￥' + ${#numbers.formatDecimal(item.price, 1, 2)}">单价</td>
                    <td th:text="${item.quantity}">数量</td>
                    <td>
                        <span th:text="${item.inventory}"
                              th:class="${item.inventory lt item.quantity ? 'text-danger' : ''}">
                        </span>
                        <span th:if="${item.inventory lt item.quantity}" class="text-danger">(库存不足)</span>
                    </td>
                    <td th:text="'￥' + ${#numbers.formatDecimal(item.totalPrice, 1, 2)}">总价</td>
                    <td th:text="${item.supplierName}">供应商</td>
                </tr>
                </tbody>
            </table>
        </div>
        <div th:if="${order != null and canRate}">
            <button id="openRatingBtn"
                    class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition">
                立即评价
            </button>
            <span th:if="${order.items[0].supplierId == null}"
                  class="text-red-500">无法评价：供应商ID缺失</span>
        </div>

        <div class="order-actions">
            <form th:action="@{'/buyer/pay/' + ${order.orderNo}}" method="post" th:if="${order.status == 'PENDING'}" id="payForm">
                <input type="hidden" name="paymentMethod" id="paymentMethodInput" th:value="${order.paymentMethod}"/>
                <button type="submit" class="btn-pay">立即支付</button>
            </form>
            <form th:action="@{'/buyer/cancel/' + ${order.orderNo}}" method="post" th:if="${order.status == 'PENDING'}">
                <button type="submit" class="btn-cancel">取消订单</button>
            </form>
            <form th:action="@{'/buyer/confirm/' + ${order.orderNo}}" method="post" th:if="${order.status == 'SHIPPED'}">
                <button type="submit" class="btn-confirm">确认收货</button>
            </form>
            <script>
                $(document).ready(function() {
                    $('#confirmForm').on('submit', function(e) {
                        e.preventDefault();
                        $.ajax({
                            type: 'POST',
                            url: $(this).attr('action'),
                            success: function(response) {
                                window.location.reload();
                            },
                            error: function(xhr) {
                                alert('确认收货失败: ' + xhr.responseText);
                            }
                        });
                    });
                });
            </script>
        </div>
        <div class="order-back">
            <button class="btn-back" onclick="window.location.href='/buyer/list'">返回订单列表</button>
        </div>
    </div>
</div>
<!-- 评价弹窗 -->
<div id="ratingModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center hidden z-50">
    <div class="bg-white rounded-lg shadow-lg w-full max-w-lg p-6 relative">
        <button class="absolute top-2 right-2 text-gray-500 hover:text-gray-700 text-2xl" id="closeRatingBtn">×</button>
        <h2 class="text-xl font-bold mb-4">评价供应商</h2>

        <form th:action="@{/buyer/rating/submit}" method="post" th:object="${supplierRatingDto}" onsubmit="return validateForm()">
            <input type="hidden" name="orderId" th:value="${order.id}" />
            <input type="hidden" name="supplierId" th:value="${order.items[0].supplierId}" />
            <input type="hidden" name="orderNo" th:value="${order.orderNo}" />

            <div class="mb-4">
                <label class="block text-gray-700 font-medium mb-2">评分（必填）</label>
                <div class="flex space-x-1 text-2xl" id="star-container">
                    <i class="fas fa-star cursor-pointer text-gray-300" data-value="1"></i>
                    <i class="fas fa-star cursor-pointer text-gray-300" data-value="2"></i>
                    <i class="fas fa-star cursor-pointer text-gray-300" data-value="3"></i>
                    <i class="fas fa-star cursor-pointer text-gray-300" data-value="4"></i>
                    <i class="fas fa-star cursor-pointer text-gray-300" data-value="5"></i>
                    <input type="hidden" name="rating" id="ratingInput" value="0"/>
                </div>
            </div>

            <div class="mb-4">
                <label class="block text-gray-700 font-medium mb-2">评价内容</label>
                <textarea name="comment" class="w-full border border-gray-300 rounded px-3 py-2" rows="4"
                          placeholder="请输入您的评价内容..."></textarea>
            </div>

            <div class="text-right">
                <button type="submit" class="px-4 py-2 bg-green-600 text-white rounded hover:bg-green-700">提交评价</button>
            </div>
        </form>
    </div>
</div>
<!-- 评价成功提示弹窗 -->
<div class="success-modal-overlay" id="successModalOverlay">
    <div class="success-modal">
        <h3>评价成功</h3>
        <button class="btn-confirm" id="successModalConfirm">确定</button>
    </div>
</div>

<script>
    $(document).ready(function () {
        // 打开评价弹窗
        $('#openRatingBtn').click(function () {
            $('#ratingModal').removeClass('hidden');
        });

        // 关闭评价弹窗
        $('#closeRatingBtn').click(function () {
            $('#ratingModal').addClass('hidden');
        });

        // 星级评分逻辑
        $('#star-container i').click(function () {
            const rating = $(this).data('value');
            $('#ratingInput').val(rating);
            $('#star-container i').removeClass('text-yellow-400').addClass('text-gray-300');
            $(this).prevAll().addBack().removeClass('text-gray-300').addClass('text-yellow-400');
        });

        // 提交评价表单
        $('form[action="/buyer/rating/submit"]').submit(function(e) {
            e.preventDefault();
            $.ajax({
                type: 'POST',
                url: $(this).attr('action'),
                data: $(this).serialize(),
                success: function(response) {
                    // 关闭评价弹窗
                    $('#ratingModal').addClass('hidden');
                    // 显示成功弹窗
                    $('#successModalOverlay').fadeIn();
                },
                error: function(xhr) {
                    alert('评价失败: ' + xhr.responseText);
                }
            });
        });
        // 关闭成功弹窗
        $('#successModalConfirm').click(function() {
            $('#successModalOverlay').fadeOut();
        });
    });

    function validateForm() {
        const rating = $('#ratingInput').val();
        if (rating === "0") {
            alert("请给出评分！");
            return false;
        }
        return true;
    }

    // 支付表单提交逻辑
    $('#payForm').on('submit', function(e) {
        e.preventDefault();

        const selectedPaymentMethod = $('#paymentMethodSelect').val();
        $('#paymentMethodInput').val(selectedPaymentMethod);
        console.log("提交的 paymentMethod:", selectedPaymentMethod);

        let hasInsufficientStock = false;
        $('tr').each(function() {
            const quantity = parseInt($(this).find('td:nth-child(4)').text());
            const inventory = parseInt($(this).find('td:nth-child(5) span:first').text()) || 0;
            if (quantity > inventory) {
                hasInsufficientStock = true;
                return false;
            }
        });

        if (hasInsufficientStock) {
            alert('部分商品库存不足，无法完成支付！');
            return;
        }

        var formData = $(this).serialize();
        console.log("提交的表单数据:", formData);
        $.ajax({
            type: 'POST',
            url: $(this).attr('action'),
            data: formData,
            dataType: 'json',
            success: function(response) {
                console.log("支付成功，返回响应:", response);
                if (response.success) {
                    window.location.href = response.redirectUrl;
                } else {
                    alert(response.message);
                }
            },
            error: function(xhr) {
                console.error("支付失败:", xhr.responseText);
                alert('支付失败: ' + xhr.responseText);
            }
        });
    });

    $('#paymentMethodSelect').on('change', function() {
        $('#paymentMethodInput').val($(this).val());
        console.log("select 变化，新的 paymentMethod:", $(this).val());
    });
</script>
<th:block th:replace="~{/footer.html}"></th:block>
<script src="/js/jquery-latest.min.js"></script>
<script src="/js/popper.min.js"></script>
<script src="/js/bootstrap.min.js"></script>
</body>
</html>
